<?php


namespace app\admin\business;

use app\common\model\mysql\Category as CategoryModel;
use think\Exception;

class Category
{
    public $model = [];
    public function __construct(){
        $this->model = new CategoryModel();
    }

    /** 新增商品
     * @param $data
     * @return mixed
     */
    public function add($data){
        $data['status'] = config('status.mysql.table_normal');
        $name = $data['name'];
        // 根据$name 去数据库查询是否存在这条记录
        try {
            $this->model->save($data);
        }catch (\Exception $e){
            throw new Exception('服务器内部异常');
        }
        return $this->model->id;
    }

    public function getNormalCategories(){
        $field = 'id,name,pid';
        $categories = $this->model->getNormalCategories($field);
        if (!$categories){
            $categories = [];
        }
        return $categories->toArray();
    }

    public function getLists($data, $num) {
        $list = $this->model->getLists($data,$num);
        if (!$list){
            return [];
        }
        $result =  $list->toArray();
        $result['render'] = $list->render();
        return $result;
    }

    /**
     * 根据id获取某一条记录
     * @param $id
     * @return array
     */
    public function getById($id){
        $result = $this->model->find($id);
        if (empty($result)){
            return [];
        }
        return $result->toArray();
    }

    public function listorder($id,$listorder){
        $res = $this->getById($id);
        if (!$res){
            throw new Exception('不存在该记录');
        }
        $data = [
            'listorder' => $listorder
        ];
        try {
            $res = $this->model->updateById($id,$data);
        }catch (\Exception $e){
            // 记录日志
            return false;
        }
        return $res;
    }

    /**
     * 更改状态
     * @param $id
     * @param $status
     * @return bool
     * @throws Exception
     */
    public function status($id,$status){
        $res = $this->getById($id);
        if (!$res){
            throw new Exception('不存在该记录');
        }
        if ($res['status'] == $status){
            throw new Exception('状态无意义');
        }
        $data = [
            'status' => intval($status)
        ];
        try {
            $res = $this->model->updateById($id,$data);
        }catch (\Exception $e){
            // 记录日志
            return false;
        }
        return $res;
    }

    /**
     * 删除方法 软删除
     * @param $id
     * @return bool
     */
    public function del($id){
        return CategoryModel::destroy($id);
    }
}